<?php
/**
 * Created by PhpStorm.
 * User: tom_xia
 * Date: 2018/1/10
 * Time: 15:48
 * 定义:该类代表一个队列。如果要使用多个不同的队列 需要多次实例化
 */

namespace app\cls\tom;




class Queue
{
    /**
     * @var \Redis 实例
     */
    private $redis;
    /**
     * @var string 队列名字
     */
    private $queueName = "";
    /**
     * @var int 队列总数
     */
    private $queueNum = 5;
    /**
     * @var string 队列公共前缀
     */
    private $queuePrefix = REDIS_PREFIX."QUEUE_LIST_";


    /**
     * @param \Redis $redis
     */
    public function setRedis($redis)
    {
        $this->redis = $redis;
    }

    /**
     * @param string $queueName
     */
    public function setQueueName($queueName)
    {
        $this->queueName = $queueName;
    }

    /**
     * @param int $queueNum
     */
    public function setQueueNum($queueNum)
    {
        $this->queueNum = $queueNum;
    }

    /**
     * @return string
     */
    public function getQueueName()
    {
        return $this->queueName;
    }

    /**
     * @return int
     */
    public function getQueueNum()
    {
        return $this->queueNum;
    }

    /**
     * @return string
     */
    public function getQueuePrefix()
    {
        return $this->queuePrefix;
    }


    public function __construct(\Redis $redis,$queueName)
    {
        $this->redis = $redis;
        $this->queueName = $queueName;
    }

    /**
     * @param $data
     * @return int 入队列
     */
    public function push($data,$uuid,$style = "left"){
        $queueName = $this->getHashSuffixByUUID($uuid);
        if($style == "left"){
            return $this->redis->lPush($queueName,$data);
        }else{
            return $this->redis->rPush($queueName,$data);
        }
    }

    /**
     * @return string 出队列
     */
    public function pop($queue){
        if(intval($queue) > $this->queueNum - 1){
            return null;
        }
        return $this->redis->rPop($this->queuePrefix.$this->queueName."_".$queue);
    }

    /**
     * @desc 通过用户的uuid获得存储用户信息的redis hash表名或者队列名称
     * @return string hash key
     */
    private  function getHashSuffixByUUID($uuid)
    {
        //1.获取uuid的循环冗余码,并取正整数
        $code = sprintf("%u",crc32($uuid));
        //2.获取hash表后缀
        if($this->queueNum == 1){
            $hashSuffix = 0;
        }else{
            $hashSuffix = $code % $this->queueNum;
        }
        $queueFinalName =  $this->queuePrefix.$this->queueName."_".$hashSuffix;
        return $queueFinalName;
    }

}